//
//  DAOtherPersonalViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/5/25.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAOtherPersonalViewController.h"
#import "DAloginPersonalInformation.h"
#import "DAPersonalBorrowBookTableViewCell.h"
#import "DAPersonalBookHistoryTableViewCell.h"
#import "DAHomePageTimeLineModel.h"
#import "DAHomePageShowBookDetailViewController.h"
#import "DASearchBookDetailViewController.h"
#import "DAPersonalBackBookTableViewCell.h"
#import "DAPersonalFileUploadTableViewCell.h"
#import "DAWebFileViewController.h"

@interface DAOtherPersonalViewController ()<UITableViewDataSource, UITableViewDelegate,clickBookImage, personalBckBookClickBookImage, PersonalFileUploadDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backWallImage;
@property (weak, nonatomic) IBOutlet UIImageView *userImage;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *userSigature;
@property (nonatomic, strong) DAloginPersonalInformation *personalInformation;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *backView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, copy) NSString *userBackground;
@property (nonatomic, copy) NSString *userFace;
@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *userSign;

@property(nonatomic, strong) DAHomePageShowBookDetailViewController *detailView;
/** 灰色蒙版*/
@property (nonatomic, strong) UIView *grayView;

@property (nonatomic, assign) NSInteger pageNumber;

@property (nonatomic) BOOL isRefresh;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;

@property (nonatomic, strong) DAPersonalBackBookTableViewCell * backCell;
@property (nonatomic, strong) DAPersonalBookHistoryTableViewCell *borrowCell;


@end

@implementation DAOtherPersonalViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [SVProgressHUD dismiss];
  //  [self prepareData];
    [self setNotfic];
    
}
- (void)setNotfic{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grayViewRemoveSuperView) name:@"GRAYVIEWREMOVESUPERVIEW" object:nil];
    
}
- (void)grayViewRemoveSuperView{
    [self.grayView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    // 准备数据
   //[self prepareData];
    // 创建 tableView
    [self creatTableView];
    // 创建 detailBookView
    [self buildBookDetailView];
    self.pageNumber = 0;
    self.dataArray = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherPersonalRefresh:) name:@"OtherPersonalRefresh" object:nil];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)otherPersonalRefresh:(NSNotification *)not{
    [self clickClose:nil];
    self.otherUserID = not.object;
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark - 设置
- (void)configPageView{
   // [self.backWallImage sd_setImageWithURL:[NSURL URLWithString:self.userBackground]];

   // [self.backWallImage sd_setImageWithURL:[NSURL URLWithString:self.userBackground] placeholderImage:[UIImage imageNamed:@"holderback"] options:SDWebImageRefreshCached];
    self.backWallImage.image = [UIImage imageNamed:@"background.jpg"];
    //[self.userImage sd_setImageWithURL:[NSURL URLWithString:self.userFace]];
    [self.userImage sd_setImageWithURL:[NSURL URLWithString:self.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
    self.userImage.layer.cornerRadius = 30;
    self.userImage.clipsToBounds = YES;
    if ([self.userName isKindOfClass:[NSNull class]]) {
        
    }else{
        self.userNameLabel.text = self.userName;
        self.userNameLabel.textColor = [UIColor whiteColor];
        self.userNameLabel.textAlignment = NSTextAlignmentCenter;
    }
    if ([self.userSign isKindOfClass:[NSNull class]]) {
       // self.userSigature.text = self.userSign;
    }else{
        self.userSigature.textColor = [UIColor whiteColor];
        self.userSigature.font = [UIFont systemFontOfSize:12];
        self.userSigature.textAlignment = NSTextAlignmentCenter;
        self.userSigature.text = self.userSign;
    }

}
#pragma mark - tableView设置
- (void)creatTableView{
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.backView.frame = CGRectMake(0, -64, self.view.frame.size.width, 200);
    self.backView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableView.tableHeaderView = self.backView;
    // 上拉
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = self.footer;
    self.tableView.mj_footer.hidden = YES;
    
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    
  //  self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    
}
#pragma mark - refreshData
- (void)refreshData{
    self.pageNumber = 0;
    self.isRefresh = YES;
    [self prepareData];
}
#pragma mark - loadMoreData
- (void)loadMoreData{
    self.isRefresh = NO;
    [self prepareData];
}
//==================================网络请求和数据处理=============================================
#pragma mark - 数据准备
- (void)prepareData{
    NSString *url = DAPersonalTimeLineURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", (long)self.pageNumber];
    NSDictionary *dic = @{@"userID":self.otherUserID,
                          @"page": pageNumber};
    NSLog(@"%ld", (long)self.pageNumber);
    
     [self dataHandelWithUrl:url parame:dic];
}
#pragma mark - 网络请求
- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)parame{
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:parame cookie:nil result:^(id result) {
        if (result && [result[@"result"] isKindOfClass:[NSArray class]]) {
            if ([result[@"result"] count] < 20) {
               // self.footer.stateLabel.hidden = YES;
                weakSelf.tableView.mj_footer.hidden = YES;
            }else{
               // self.footer.stateLabel.hidden = NO;
                weakSelf.tableView.mj_footer.hidden = NO;
            }
            // 数据转换model
            [weakSelf dataTransformModel:result[@"result"] dictionary:result];
              weakSelf.pageNumber++;
        }else{
            //[SVProgressHUD showErrorWithStatus:@"没有更多数据"];
             NSLog(@"DAPersonalTimeLineURL:没有更多数据。");
            if (weakSelf.isRefresh) {
                [weakSelf.tableView.mj_header endRefreshing];
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            else{
                //[SVProgressHUD showErrorWithStatus:@"请求数据失败"];
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
    }];
}
#pragma mark - 数据转model
- (void)dataTransformModel:(NSArray *)dataArray dictionary:(NSDictionary *)dictionary{
    DAHomePageTimeLineModel *otherPageTimeLine = [[DAHomePageTimeLineModel alloc]init];
    NSArray *array = [otherPageTimeLine returnModelInArrayWithDic:dataArray];
    if (self.isRefresh) {
        self.dataArray = [NSMutableArray array];
        [self.dataArray addObjectsFromArray:array];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }
    else{
        [self.dataArray addObjectsFromArray:array];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }
    self.userBackground = dictionary[@"userBackground"];
    self.userFace = dictionary[@"userFace"];
    self.userName = dictionary[@"userName"];
    self.userSign = dictionary[@"userSign"];
    [self configPageView];
   
    
}
//==========================================End===================================================

#pragma mark - tablView 协议方法
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 60, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 60, 0, 0)];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
        self.backCell = [tableView dequeueReusableCellWithIdentifier:@"otherPersonalBackBook"];
        if (self.backCell == nil) {
            self.backCell = [[DAPersonalBackBookTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"otherPersonalBackBook"];
        }
        self.backCell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
        self.backCell.timeLineModel = self.dataArray[indexPath.row];
        self.backCell.delegate = self;
        return self.backCell;
    }
    else{
        if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"1"]) {
            self.borrowCell = [tableView dequeueReusableCellWithIdentifier:@"otherHistory"];
            if (self.borrowCell == nil) {
                self.borrowCell = [[DAPersonalBookHistoryTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"otherHistory"];
            }
            self.borrowCell.selectionStyle = UITableViewCellSelectionStyleNone;
            self.borrowCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
            self.borrowCell.timeLineModel = self.dataArray[indexPath.row];
            self.borrowCell.delegate = self;
            return self.borrowCell;
        } else if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"3"]){
            DAPersonalFileUploadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OtherPersonalFileUpload"];
            if (cell == nil) {
                cell = [[DAPersonalFileUploadTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OtherPersonalFileUpload"];
            }
            cell.model = self.dataArray[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
            cell.delegate = self;
            return cell;
        }
        else{
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"sss"];
            return cell;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
        CGFloat textHeight = [self heightWithText:[self.dataArray[indexPath.row] rateMessage] Width:[UIScreen mainScreen].bounds.size.width - 125 Font:12];
        return 145 + textHeight + 48;
        
    }else{
        if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"1"]) {
            return 155;
        }else if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"3"]){
            return 110;
        }
        else{
            return 0;
        }
        
    }
    
}
#pragma mark - 点击图书image 的协议方法
- (void)clickBookImage:(NSString *)bookId{
    [self showGrayView];
    [self creatBookDetailView];
    self.detailView.bookID = bookId;
    self.detailView.isSelectHomePageTimeLine = NO;
    self.detailView.isSelectPersonalPage = NO;
    self.detailView.isSelectOtherPersonalPage = YES;
    [self.detailView prepareData];
    [self.detailView.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark - 归还的cell 点击图书image的协议方法
- (void)personalBackBookClickBookImage:(NSString *)bookID{
    [self showGrayView];
    [self creatBookDetailView];
    self.detailView.bookID = bookID;
    self.detailView.isSelectHomePageTimeLine = NO;
    self.detailView.isSelectPersonalPage = NO;
    self.detailView.isSelectOtherPersonalPage = YES;
    [self.detailView prepareData];
    [self.detailView.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark - 弹出的图书详情页面
- (void)buildBookDetailView{
    self.detailView = [self.storyboard instantiateViewControllerWithIdentifier:@"BOOKDETAIL"];
    self.detailView.view.frame = CGRectMake(20, 80, self.view.frame.size.width - 40, 400 * HEIGHTTOFIT5s);
    [[UIApplication sharedApplication].keyWindow addSubview:self.detailView.view];
    self.detailView.view.hidden = YES;
}
- (void)showGrayView{
    /** 灰色蒙版*/
    self.grayView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.grayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:self.grayView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClose:)];
    [self.grayView addGestureRecognizer:tap];
}
- (void)creatBookDetailView{
    self.detailView.view.hidden = NO;
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.detailView.view];
    /** 添加动画*/
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.detailView.view cache:YES];
    [UIView commitAnimations];
    /** 消失手势*/
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClose:)];
    [self.detailView.closeImage addGestureRecognizer:tap];
    /** bookImage手势*/
    UITapGestureRecognizer *bookImageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickBookImageShow:)];
    self.detailView.bookImage.userInteractionEnabled = YES;
    [self.detailView.bookImage addGestureRecognizer:bookImageTap];
}
#pragma mark - 点击closeImage触发的方法
- (void)clickClose:(UITapGestureRecognizer *)tap{
    NSLog(@"关闭");
    self.detailView.view.hidden = YES;
    [self.grayView removeFromSuperview];
}
#pragma mark - 点击bookImage触发的方法
- (void)clickBookImageShow:(UITapGestureRecognizer *)tap{
    /** 跳转到图书详情页面*/
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    DASearchBookDetailViewController *detailVC = [story instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
    detailVC.bookID = self.detailView.bookID;
    [self clickClose:nil];
    detailVC.hidesBottomBarWhenPushed = YES;
    /** 转场动画
     *CTransition *transition = [CATransition animation];
     *transition.duration = 1.0f;
     *transition.type = @"rippleEffect";
     *transition.subtype = kCATransitionFromTop;
     *[self.navigationController.view.layer addAnimation:transition forKey:nil];
     */
    /** push之前先关掉隐藏导航栏*/
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - PersonalFileUploadDelegate
- (void)personalOpenFieldWithModel:(DAHomePageTimeLineModel *)model{
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.timelinefolderName,model.timelinefileExtend];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
    webFile.fileUrl = filePath;
    webFile.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webFile animated:YES];
}
- (void)dealloc{
    self.tableView.delegate = nil;
    self.backCell.delegate = nil;
    self.borrowCell.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GRAYVIEWREMOVESUPERVIEW" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"OtherPersonalRefresh" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
